$(function(){
	$W = $(window).width();
	$H = $(window).height();
	w = $(".window").width(); 
	h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
	$("#bartd_total").attr("nid",dsId);
	setInterval("getDownloadProcessBar()", 2500);
});

var dsId = getUrlParam("dsId");
var version = getUrlParam("version");
var path = getUrlParam("path");
var root=decodeURI(getUrlParam("root"));

var href = unescape(window.location.href);
var idx = href.lastIndexOf("dir=");
if(idx!=-1){
	path = href.substring(idx+4);
}

if (!path) {
    path = "/";
}
$('#currentPath').attr("value", path);
var parentPath = path;
if (path != "/") {
    parentPath = path.substring(0, path.lastIndexOf("\\"));
}
var url = "file_list.html?dsId=" + dsId + "&path=" + parentPath + "&version=" + version+"&dir="+escape(parentPath);
$('#back').attr("href", url);
var dsCB = function (data) {
    var json = eval("(" + data + ")");

    var str = '';
    for (i = 0; i < json.length; i++) {
        var f = json[i];
        var path = f.path.split("\\").join('\\\\');
        var fileSize = "---";
        if(f.type == "文件"){
        	fileSize = f.fileSize;
        	if(f.fileSize/1024 > 1){
        		fileSize = f.fileSize/1024.0;
        		fileSize = fileSize.toFixed(2);
        		fileSize += "KB";
        	}else{
        		fileSize += "B";
        	}
        	if(f.fileSize/(1024*1024) > 1){
        		fileSize = f.fileSize/(1024.0*1024);
        		fileSize = fileSize.toFixed(2);
        		fileSize += "MB";
        	}
        	if(f.fileSize/(1024*1024*1024) > 1){
        		fileSize = f.fileSize/(1024.0*1024*1024);
        		fileSize = fileSize.toFixed(2);
        		fileSize += "GB";
        	}
        }
        
        var status = f.status;
        if(status == "删除"){
        	status = "<font color='red'>删除</font>";
        }
       
//        if(f.status != "删除"){
        	 if (f.type == "文件夹") {
                // str += "<tr><td><a href='file_list.html?dsId=" + dsId + "&path=" + f.path + "&version=" + version + "&dir=" + escape(f.path) +"'>" + f.name + "<br>" + f.path + "</a></td>";
                 str += "<tr><td><a href='file_list.html?dsId=" + dsId + "&root="+ encodeURI(encodeURI(root))+"&path=" + f.path + "&version=" + version + "&dir=" + escape(f.path) +"'>" + f.name + "<br>" + f.path + "</a></td>";
        	 } else {
                 str += "<tr><td>" + f.name + "<br>" + f.path + "</a></td>";
             }
             str += "<td>" + f.type + "【"+status+"】</td>";
             str += "<td>" + fileSize + "</td>";
             str += "<td><span class='tipspan'></span></td>";
             if(f.type == "文件夹"){
             	str += "<td nid='"+f.nid+"' class='bartd' id='bartd"+i+"'><button class='btn' onclick='directors(\""+dsId+"\",\""+path+"\",\""+version+"\",\""+f.name+"\",\"bartd"+i+"\",\""+f.nid+"\")'>点击恢复</button></td>"
             }else{
             	str += "<td nid='"+f.nid+"' class='bartd' id='bartd"+i+"'><button class='btn' onclick='files(\""+dsId+"\",\""+path+"\",\""+version+"\",\""+f.name+"\",\"bartd"+i+"\",\""+f.nid+"\")'>点击恢复</button></td>"
             }
             str += "</tr>";
//        }

    }
    $("#fBody").html(str);
    $("#fBody").find("tr:odd").find("td").css("background","#fafafa");
    
    getDownloadProcessBar();
    //$('#content').html(str);
};

function getDownloadProcessBar() {

	var ids = "";
	$(".bartd").each(function() {
		ids += $(this).attr("nid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		service.getDownloadProcessBar(ids, processbarCB);
		service.deleteDownloadProcessBar(ids, delProcessbarCB);
	}
}

function recoveryWholeDs(bartd_id){
	$("#h_nid").val(dsId);
	directors(dsId,"/",version,"",bartd_id);
}
function toRecoveryPage(){
	window.location.href="recovery.html";
}
function getBackupWrapper(dsId) {
	var backupLog = {
		dsId : dsId,
		status:0
	}
	var pages = {
		startPos : 0,
		pageSize : 5
	}
	var json = {};
	json["backupLog"] = backupLog;
	json["pages"] = pages;

	return json;
}
var backupLogCB = function(data){
	var data = eval("(" + data + ")");
	var list = data.list.objList;
	var size = list.length;
	var content = "";
	for (var i = 0; i < size; i++) {
		obj = list[i];
		content = content
		+"<li>" 
		+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\"),setHideVersion(\""+obj.versionMajor+".0\")' class='btn'>恢复至</button></span>"
		+"<span style='float:right;'>"+new Date(obj.beginTime).toLocaleString()+"</span>"
		+"</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
};
function directors(dsId,path,version,name,bartd_id,nid){
	$("#h_dsId").val(dsId);
	$("#h_path").val(path);
	$("#h_bartd_id").val(bartd_id);
	if(nid){
		$("#h_nid").val(nid);
	}
	service.getBackuplogs(getBackupWrapper(dsId), backupLogCB);
	
}
function files(dsId,path,version,name,bartd_id,nid){
	$("#h_dsId").val(dsId);
	$("#h_bartd_id").val(bartd_id);
	$("#h_path").val(path+"\\"+name);
	if(nid){
		$("#h_nid").val(nid);
	}
	var service1 = new EbeimService();
	service1.getFileChangeLog(dsId, encodeURIComponent(encodeURIComponent(path)), version, encodeURIComponent(encodeURIComponent(name)), fileChangeLogBC);
}
var fileChangeLogBC = function (data) {
	/* $('#myModal').modal("show"); */
    var jsonStr = eval("(" + data + ")");
    var json = eval("(" + jsonStr + ")");
	var list = json.list.objList;
	
	var content = "";
	for (var i = 0; i < (list.length>5?5:list.length); i++) {
		var obj = list[i];
		content = content
		+"<li>"
		+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\"),setHideVersion(\""+obj.version+"\")' class='btn'>恢复至</button></span>"
		+"<span style='float:right;'>"+new Date(obj.logTime).toLocaleString()+"</span>"
		+"</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
	
//	selectRecoveryPath("");
	
};
function setHideVersion(version){
	$("#h_version").val(version);
}
function selectParentPath(path){
	var abDir = $("#ab-dir").html();
	var idx = abDir.lastIndexOf("\\");
	if(idx!=-1){
		abDir = abDir.substring(0,idx);
		$("#ab-dir").html(abDir);
    	service.getSystemDirs(abDir, selectRecoveryPathCB);
	}else{
		$("#ab-dir").html("");
		service.getSystemDirs("", selectRecoveryPathCB);
	}
}
var selectParentPathCB = function(data){
	var json = eval("("+data+")");
	var content = "";
	for (var i = 0; i < json.length; i++) {
		content = content +
		"<li><a href='javascript:selectRecoveryPath(\""+json[i].name+"/\")'>"+json[i].name+"</a></li>";
	}
	$(".w-dir-list ul").html(content);
}

function selectRecoveryPath(path){
	$(".window").css("display","block");
	$(".shadowDiv").css("display","block");
	var abDir = $("#ab-dir").html();
	if(abDir!=""){
		$("#ab-dir").html(abDir+"\\"+path);
		service.getSystemDirs(abDir+"\\"+path, selectRecoveryPathCB);
	}else{
		$("#ab-dir").html(path);
		service.getSystemDirs(path, selectRecoveryPathCB);
	}
}
var selectRecoveryPathCB = function(data){
	var json = eval("("+data+")");
	var content = "";
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		if(i==0){
			 var name = name.split("\\").join("\\\\");
		}
		content = content +
		"<li><a href='javascript:selectRecoveryPath(\""+name+"/\")'>"+name+"</a></li>";
	}
	$(".w-dir-list ul").html(content);
}

function confirmDir(){
	var version = $("#h_version").val();
	recovery(version);
}
function cancelDir(){
	clearDateAndWindow();
}

function recovery(version,dynamicCode){
	var dsId = $("#h_dsId").val();
	var path ="/"+$("#h_path").val();
	var abDir = $("#ab-dir").html();
	var nid = $("#h_nid").val();
	if(abDir == ""){
		alert("请选择下载目录");
		return;
	}
	$("#recoveyBtn").attr("disabled","disabled");
	service.recoveryFile(dsId, encodeURIComponent(encodeURIComponent(path))
			, version,dynamicCode,encodeURIComponent(encodeURIComponent(abDir)), recoveryCB,nid);
}
function setDynamicCode(){
	var dynamicCode = $("#dynamicCode").val();
	if(dynamicCode == ""){
		alert("动态验证码不能为空!");
		return;
	}
	var version = $("#h_version").val();
	recovery(version,dynamicCode);
}
function clearDateAndWindow(){
	$("#dynamicCode").val("");
	$("#ab-dir").html("");
	
	hideDialog("versionWindow");
	$('#myModal').modal("hide");
	$(".window").css("display","none");
	$(".shadowDiv").css("display","none");
}
var recoveryCB = function(data){
	$("#recoveyBtn").removeAttr("disabled");
	var json = eval("("+data+")");
	if(json.code=="200" || json.code==200){
		
		clearDateAndWindow();
		
		var td_id = $("#h_bartd_id").val();
    	$("#"+td_id).parent().find("td").find(".tipspan").html("等待链接...");
   		var content = ""
   		+"<div style='width:200px;height:20px;border:solid 1px #B8C86C;margin:0 auto;'>"
   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
   		+"</div>正在恢复:<span id='percentage' style='color:green'>0.00%</span>";
   		
   		var td_id = $("#h_bartd_id").val();
   		$("#"+td_id).html(content);
   		
	 }else{
		 dsSecurityRankCheck(json.code,json.message);
	 }
	
} 
var processbarCB = function(data){
	var json = eval("(" + data + ")");
	var list = json.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		$(".bartd").each(function(){
			var nid = $(this).attr("nid");
			if (nid == bean.nid) {
				var count = bean.count;
				var total = bean.total;
				var percent = (count/total)*100;
				
				var content = ""
			   		+"<div style='width:200px;height:20px;border:solid 1px #B8C86C;margin:0 auto;'>"
			   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
			   		+"</div>正在恢复:<span id='percentage' style='color:green'>0.00%</span>";
				$(this).html(content);
				
				if(count >= total){
					$(this).parent().find("td").find(".tipspan").html("");
					$(this).html("下载完成!");
				}else if(count == -1){
					$(this).find(".processbar-container").find(".percent").html("<font color='red'>下载失败！</font>");
					service.deleteDownloadProcessBarByNid(nid, function(data){;});
				}else{
	    			$(this).parent().find("td").find(".tipspan").html("正在下载...");
	    			$(this).find("#processbar").css("width",percent+"%");
	    			$(this).find("#percentage").html(percent.toFixed(2)+"%");
				}
			}
		});
	}
}
var delProcessbarCB = function(data) {
	var json = eval("(" + data + ")");
}
var service = new EbeimService();
service.getFileList(dsId, version, encodeURIComponent(encodeURIComponent(path)), dsCB);